<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>图片管理</title>

    <link rel="stylesheet" href="//cdn.staticfile.org/layui/2.6.3-2/css/layui.min.css" media="all">
    <link rel="stylesheet" href="//cdn.staticfile.org/font-awesome/5.15.3/css/all.css" media="all">
    {:$search.theme}
    {:$search.style}

    <style>
        body {
            background-color: white !important;
        }

        .container{
            position: relative;
            margin: 0 auto;
            padding: 0 20px;
            box-sizing: border-box;
        }

        #img-pagination {
            width: 100%;
            text-align: center;
            margin-top: 10px;
        }

        .btns {
            margin: 20px auto;
        }

        .delay{
            display: none;
        }

        .file-box {
            float: left;
            width: 125px;
        }

        .file .icon, .file .image {
            height: 113px;
            overflow: hidden;
            text-align: center;
            position: relative;
        }

        .file .suffix {
            font-size: 10px;
            padding: 1px 5px;
            border-radius: 5px;
            background-color: rgba(103,194,58, .7);
            color: #ffffff;
        }

        .filename {
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
        }

        .file-name small {
            color: #676a6c;
        }

        .file-box .file {
            border: 1px solid #e7eaec;
            padding: 0;
            background-color: #ffffff;
            position: relative;
            margin: 5px;
        }

        .file .image > img {
            max-width: 100%;
            height: auto;
            border: 0;
            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            margin: auto;
        }

        .corner {
            position: absolute;
            display: inline-block;
            width: 0;
            height: 0;
            line-height: 0;
            border: 0.6em solid transparent;
            border-right: 0.6em solid #f1f1f1;
            border-bottom: 0.6em solid #f1f1f1;
            right: 0em;
            bottom: 0em;
        }

        .file .file-name {
            padding: 10px;
            background-color: #f8f8f8;
            border-top: 1px solid #e7eaec;
            overflow: hidden;
        }

        .checkFile .file::before {
            content: "✔";
            position: absolute;
            width: 100%;
            height: 100%;
            z-index: 99;
            background: rgba(0, 0, 0, 0.5);
            color: white;
            font-size: 40px;
            text-align: center;
            line-height: 140px;
        }

        .a-upload {
            position: relative;
            display: inline-block;
        }

        .a-upload input {
            position: absolute;
            width: 100%;
            height: 100%;
            right: 0;
            top: 0;
            opacity: 0;
        }

        #s-search-collapse {
            padding: 0px;
            margin: 0px;
            max-height: 0;
            overflow: hidden;
            background-color: #fff;
            box-shadow: 0 1px 5px 2px rgba(64%, 64%, 74%, 0.5) inset;
            transition: max-height .25s, padding .25s, margin .25s;
        }

        .btns{
            display: inline-block;
            box-shadow: 0 3px 1px -2px rgb(0 0 0 / 7%), 0 2px 2px 0 rgb(0 0 0 / 7%), 0 1px 5px 1px rgb(0 0 0 / 7%);
        }

        .btns .layui-btn{
            color: #000000;
            background: #fff;
        }

        .search-btn{
            border: none;
            border-right: 1px solid rgba(200, 200, 200, 0.3);
        }
        .search-btn.hover{
            box-shadow: 0 1px 5px 2px rgb(163 163 189 / 50%) inset;
        }
    </style>
</head>
<body class="container delay">

    <!-- 按钮触发模态框 -->
    <div class="layui-btn-group btns">
        <button type="button" class="layui-btn search-btn">
            <i class="layui-icon layui-icon-search"></i>搜索
        </button>
        <button type="button" class="layui-btn a-upload">
            <input type="file" id="fileModel"><i class="layui-icon layui-icon-upload-drag"></i>上传
        </button>
    </div>

    <div id="s-search-collapse">
        <div id="img-search"></div>
    </div>

    <div class="layui-row">
        <div class="col-sm-12" id="img-list"></div>
    </div>

    <div id="img-pagination"></div>

        <script src="//cdn.staticfile.org/layui/2.6.3-2/layui.min.js" charset="utf-8"></script>

    {:$search.script}

    <script>

        var max_count = {$max_count}
        // 上下文对象
        var surface_selection = []

        function getQueryVariable(variable, def = '')
        {
            let query = window.location.search.substring(1);
            let vars = query.split("&");
            for (let i=0;i<vars.length;i++) {
                let pair = vars[i].split("=");
                if(pair[0] == variable){return pair[1];}
            }
            return(def);
        }

        layui.use(['laypage', 'jquery', 'layer'], function () {
            let $ = layui.jquery,
                page = layui.laypage,
                initPage = false,
                fileType = '',
                selectLimit = getQueryVariable('limit', 0),
                query = {limit: 21};

            // 延迟显示 解决css样式加载延迟 页面显示异常
            $('.delay').show()

            /**
             * 插入数据
             */
            function insertData(list) {
                let _html = ''
                if (list.length <= 0) {
                    _html = "<div class='text-center'>没有更多数据~</div>";
                } else {
                    let images = $.parseJSON( `{:json_encode($ext['image'])}` )

                    for (let i of list) {
                        let file = '', suffix = ''
                        file = `<div class="image"><img alt="image" src="${i.url}"></div>`
                        if ($.inArray(i.suffix, images) !== -1) {
                            suffix = i.wh
                        } else {
                            suffix = i.suffix
                        }
                        let checked = '';
                        _html += `<div class="file-box ${checked}" data-name="${i.name}" data-url="${i.url}">
                        <div class="file">
                            ${file}
                            <div class="file-name">
                                <div class="filename" title="${i.name}">${i.name}</div><small class="suffix">${suffix}</small><div><small>${i.size_label}</small></div>
                            </div>
                        </div>
                    </div>`
                    }
                }
                $('#img-list').html(_html)

                return true
            }

            $('#img-list').on('click', '.file-box', function () {
                let url = $(this).data('url'), name = $(this).data('name')
                if (max_count == 1){
                    surface_selection = [];
                    $('.file-box').removeClass('checkFile')
                }
                if ($(this).hasClass("checkFile")) {
                    $(this).removeClass('checkFile')
                    surface_selection.forEach((v, k) => {
                        if (v.url === url) {
                            surface_selection.splice(k, 1)
                        }
                    })
                } else {
                    if (selectLimit > 0 &&  surface_selection.length >= selectLimit) {
                        layer.msg('最多选择'+selectLimit+'个文件！', {anim: 6})
                        return;
                    }
                    $(this).addClass('checkFile')
                    surface_selection.push({ url, name })
                }
            })

            function getData(params = {}, page) {
                $('html,body').animate({scrollTop: '0px'}, 500);
                for (let i in params) {
                    if (params[i]) {
                        query[i] = params[i]
                    } else {
                        delete query[i]
                    }
                }
                query.page = page
                let result = $.ajax({
                    url: "indexTable",
                    data: query,
                    dataType: "json",
                    async: false
                });
                if (result.responseJSON.code === 0) {
                    let data = result.responseJSON.data
                    showPagination(data.count)
                    insertData(data.list)
                } else {
                    alert(result.msg);
                }
            }

            function showPagination(total) {
                if (initPage) return;
                initPage = true;
                page.render({
                    elem: 'img-pagination'
                    , count: total //数据总数，从服务端得到
                    , limit: query.limit
                    , limits: [query.limit * 1, query.limit * 3, query.limit * 5]
                    , groups: 3
                    , prev: "〈"
                    , next: "〉"
                    , theme: "#666"
                    , layout: ['prev', 'page', 'next', 'limit']
                    , jump: function (obj, first) {
                        if (true !== first) {
                            query.limit = obj.limit
                            getData({}, obj.curr)
                        }
                    }
                });
            }

            // 搜索
            let searchNode = document.getElementById('img-search')
            if (searchNode) {
                let options = $.parseJSON( `{:$search['options']}` );
                options.onSubmit = function (value, then) {
                    initPage = false
                    getData(value, 1)
                }
                window.$surfaceForm = surfaceForm.create(searchNode, {options, columns: $.parseJSON( `{:$search['columns']}` )})
                window.$surfaceForm.submit()

                fileType = window.$surfaceForm.model('suffix')[0] || ''
            }

            $('.search-btn').click(function () {
                let node = document.getElementById('s-search-collapse')
                if (node){
                    let _h = node.scrollHeight
                    if (parseInt(node.style.maxHeight) + 50 >= _h) {
                        node.style.maxHeight = '0px';
                        node.style.padding = '0px';
                        node.style.margin = '0px';
                        $(this).removeClass('hover')
                    }else{
                        node.style.maxHeight = _h + 'px';
                        node.style.padding = '20px 0px 0px';
                        node.style.margin = '10px 0px';
                        $(this).addClass('hover')
                    }
                }
            })

            $('#fileModel').on('change', function () {
                let formData = new FormData();
                formData.append("file", document.getElementById("fileModel").files[0]);
                formData.append("fileType", fileType);
                $.ajax({
                    url: "upload",
                    type: "POST",
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: function (data) {
                        $(this).remove()
                        if (data.code === 0) {
                            layer.msg('上传成功！')
                            getData()
                        }else{
                            layer.msg(data.msg, {anim: 6})
                        }
                    },
                    error: function () {
                        layer.msg('上传失败！', {anim: 6})
                    }
                });
            })

        })
    </script>

</body>
</html>
